import 'package:flutterapp/Base/CusLoading.dart';
import 'package:flutterapp/Base/Util/NavigatorObserver.dart';
import 'file:///C:/Users/41784/AndroidStudioProjects/remoteCtrl/flutter_app/lib/Page/PageHome.dart';
import 'file:///C:/Users/41784/AndroidStudioProjects/remoteCtrl/flutter_app/lib/Page/PageReg.dart';
import 'package:flutterapp/UniqueIDUtil.dart';
import 'package:leancloud_storage/leancloud.dart';

class SaasManager {
  static const _APP_ID = "G8Is6zC356I9SlvxLiLR2x6g-MdYXbMMI";
  static const _APP_KEY = "6tKk4fuGuR8NymfEI3noniCI";
  static const _errHasUser = 202;
  static const _CLASS_DEVICE = "Device";
  static const _CLASS_EVENT = "Event";
  static const _CLASS_DIRECTIVE = "Directive";

  static init({bool isDebug = true}) {
    LeanCloud.initialize(_APP_ID, _APP_KEY, queryCache: new LCQueryCache());
    LCLogger.setLevel(LCLogger.DebugLevel);
  }

  static autoLogin(String name, String psw) async {
    cusLoading.show();
    LCUser user = LCUser();
    user.username = name;
    user.password = psw;

    user.signUp().then((value) async {
      cusLoading.dismiss();
      await _login(name, psw);
      MyNavigatorObserver.getInstance().navigator.pushNamedAndRemoveUntil(
            PageHome.ROUTER_NAME,
            (route) => false,
          );
    }).catchError((err) async {
      cusLoading.dismiss();
      print("SaasManager  autoLogin $err");
      if (err.code == _errHasUser) {
        await _login(name, psw);
      }
    });
  }

  static _login(String name, String psw) {
    // 登录成功
    cusLoading.show();
    LCUser.login(name, psw).then((value) async {
      UniqueIDUtil.lcUser = value;
      print("SaasManager  login curUser:${UniqueIDUtil.lcUser}");
      cusLoading.dismiss();
      try {
        await addDevice(UniqueIDUtil.deviceID);
      } catch (e) {
        print(e);
      }
      MyNavigatorObserver.getInstance()
          .navigator
          .pushNamedAndRemoveUntil(PageHome.ROUTER_NAME, (route) => false);
    }).catchError((err) {
      cusLoading.dismiss();
      print("SaasManager  _login $err");
    });
  }

  static loginOut() async {
//    todo 解绑设备
//    cusLoading.show();
    try {
      await delDevice(UniqueIDUtil.deviceID);
    } catch (e) {
      print(e);
    }
    LCUser.logout().then((value) {
//      cusLoading.dismiss();
      MyNavigatorObserver.getInstance().navigator.pushNamedAndRemoveUntil(
            PageReg.ROUTER_NAME,
            (route) => false,
          );
    }).catchError((err) {
//      cusLoading.dismiss();
      print("SaasManager  _login $err");
    });
  }

  static Future<bool> isLogin() async {
//    cusLoading.show();
    LCUser currentUser;
    try {
      currentUser = await LCUser.getCurrent();
      UniqueIDUtil.lcUser = currentUser;
      print("SaasManager  isLogin curUser:${UniqueIDUtil.lcUser}");
//      await addDevice(UniqueIDUtil.deviceID);
    } catch (e) {
//      cusLoading.dismiss();
//      await delDevice(UniqueIDUtil.deviceID);
      print("SaasManager  isLogin $e");
    }
    return currentUser != null;
  }

  static Future<LCUser> getCurrentUser() async {
    cusLoading.show();
    LCUser currentUser;
    try {
      currentUser = await LCUser.getCurrent();
      cusLoading.dismiss();
    } catch (e) {
      cusLoading.dismiss();
      print("SaasManager  getCurrentUser $e");
    }
    if (currentUser == null) {
      MyNavigatorObserver.getInstance().navigator.pushNamedAndRemoveUntil(
            PageReg.ROUTER_NAME,
            (route) => false,
          );
    }
    return currentUser;
  }

  static Future<List<LCObject>> getDeviceList() async {
//    cusLoading.show();
    print("SaasManager  getDeviceList curUser${UniqueIDUtil.lcUser}");

    List<LCObject> deviceList = [];
    try {
      LCQuery<LCObject> query = LCQuery(_CLASS_DEVICE);
      deviceList = await query.whereEqualTo("user", UniqueIDUtil.lcUser.username).find();
//      cusLoading.dismiss();
      print("SaasManager  getDeviceList $deviceList");
    } catch (e) {
      print("SaasManager  getDeviceList $e");
//      cusLoading.dismiss();
    }
    return deviceList;
  }

  static Future<LCObject> addDevice(String deviceId,
      {String label = "新设备"}) async {
    List<LCObject> queryList = [];
    try {
      LCQuery<LCObject> query = LCQuery(_CLASS_DEVICE);
      query.whereEqualTo("deviceId", deviceId);
      queryList = await query.find();
    } catch (e) {
      print(e);
    }
    if (queryList.isNotEmpty) {
      return Future.error({"msg": "当前设备已存在"});
    }

    LCObject res;
    try {
      // 构建对象
      LCObject todo = LCObject(_CLASS_DEVICE);
      // 为属性赋值
      todo["deviceId"] = deviceId;
      todo['label'] = label;
      todo['user'] = UniqueIDUtil.lcUser.username;
      // 将对象保存到云端
      res = await todo.save();
      print("SaasManager  addDevice $res");
    } catch (e) {
      print("SaasManager  addDevice $e");
    }
    return res;
  }

  static Future delDevice(String deviceId) async {
    List<LCObject> queryList = [];
    try {
      LCQuery<LCObject> query = LCQuery(_CLASS_DEVICE);
      query.whereEqualTo("deviceId", deviceId);
      queryList = await query.find();
    } catch (e) {
      print(e);
    }
    if (queryList.isEmpty) {
      return Future.error({"msg": "此设备不存在"});
    }
    var res;
    try {
      res = await queryList[0].delete();
      print("SaasManager  delDevice $res");
    } catch (e) {
      print("SaasManager  delDevice $e");
    }
    return res;
  }

  static Future<LCObject> updateDeviceLabel(String id, String label) async {
    LCObject res;
    try {
      LCObject todo = LCObject.createWithoutData(_CLASS_DEVICE, id);
      todo['label'] = label;
      res = await todo.save();
      print("SaasManager  updateDeviceLabel $res");
    } catch (e) {
      print("SaasManager  updateDeviceLabel $e");
    }
    return res;
  }

  static Future<List<LCObject>> getDirectiveList() async {
    print("SaasManager  getDirectiveList curUser${UniqueIDUtil.lcUser}");
//    cusLoading.show();
    List<LCObject> directiveList = [];
    try {
      LCQuery<LCObject> query = LCQuery(_CLASS_DIRECTIVE);
      directiveList = await query.whereEqualTo("user", UniqueIDUtil.lcUser.username).find();
//      cusLoading.dismiss();
      print("SaasManager  getDirectiveList $directiveList");
    } catch (e) {
      print("SaasManager  getDirectiveList $e");
//      cusLoading.dismiss();
    }
    return directiveList;
  }

  static Future<LCObject> addDirective(String label, String directiveCode,
      {String directiveArgs = ""}) async {
    LCObject res;
    try {
      // 构建对象
      LCObject todo = LCObject(_CLASS_DIRECTIVE);
      // 为属性赋值
      todo["code"] = directiveCode;
      todo["args"] = directiveArgs;
      todo['label'] = label;
      todo['user'] = UniqueIDUtil.lcUser.username;
      // 将对象保存到云端
      res = await todo.save();
      print("SaasManager  addDirective $res");
    } catch (e) {
      print("SaasManager  addDirective $e");
    }
    return res;
  }

//  static upDateDirective() {}

  static Future delDirective(String objId) async {
    var res;
    try {
      LCObject todo = LCObject.createWithoutData(_CLASS_DIRECTIVE, objId);
      res = await todo.delete();
      print("SaasManager  delDirective $res");
    } catch (e) {
      print("SaasManager  delDirective $e");
    }
    return res;
  }

  static Future<List<LCObject>> getEventLogList() async {
    List<LCObject> eventList = [];
    try {
      LCQuery<LCObject> query = LCQuery(_CLASS_EVENT);
      eventList = await query.whereEqualTo("user", UniqueIDUtil.lcUser.username).find();
      print("SaasManager  getEventLogList $eventList");
    } catch (e) {
      print("SaasManager  getEventLogList $e");
    }
    return eventList;
  }

  static Future<LCObject> addEvent(
    int succeed,
    String eventStr,
  ) async {
    LCObject res;
    try {
      // 构建对象
      LCObject todo = LCObject(_CLASS_EVENT);
      // 为属性赋值
      todo["event"] = eventStr;
      todo["status"] = succeed;
      todo['user'] = UniqueIDUtil.lcUser.username;
      // 将对象保存到云端
      res = await todo.save();
      print("SaasManager  addEvent $res");
    } catch (e) {
      print("SaasManager  addEvent $e");
    }
    return res;
  }

  static Future clearEvent(String eventStr) async {
    LCObject res;
    List<LCObject> eventList = [];
    try {
      LCQuery<LCObject> query = LCQuery(_CLASS_EVENT);
      eventList = await query.whereEqualTo("user", UniqueIDUtil.lcUser.username).find();
      res = await LCObject.deleteAll(eventList);
      print("SaasManager  clearEvent $res");
    } catch (e) {
      print("SaasManager  clearEvent $e");
    }
    return res;
  }
}
